package cn.edu.gdpt.mobile0123456789hwh0526;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class StudentDBProvider extends ContentProvider {
//    定义Uri适配器
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    static {//静态代码，加载类时执行
        matcher.addURI("cn.edu.gdpt.mobile0123456789hwh0526.StudentProvider","insert",1);
        matcher.addURI("cn.edu.gdpt.mobile0123456789hwh0526.StudentProvider","delete",2);
        matcher.addURI("cn.edu.gdpt.mobile0123456789hwh0526.StudentProvider","update",3);
        matcher.addURI("cn.edu.gdpt.mobile0123456789hwh0526.StudentProvider","query",4);
    }
    private MySQLiteOpenHelper openHelper=null;
    @Override
    public boolean onCreate() {
        openHelper=new MySQLiteOpenHelper(getContext(),"student.db",null,1);
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
        if(matcher.match(uri)==4){
            SQLiteDatabase database=openHelper.getWritableDatabase();
            return database.query("users",null,null
                    ,null,null,null,null);
        }else {
            return null;
        }
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        if(matcher.match(uri)==1){
            SQLiteDatabase database=openHelper.getWritableDatabase();
            database.insert("users",null,contentValues);
        }
        return null;
    }
    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        if(matcher.match(uri)==2){
            SQLiteDatabase database=openHelper.getWritableDatabase();
            return  database.delete("users",s,strings);
        }else {
            return 0;
        }
    }
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        if(matcher.match(uri)==3){
            SQLiteDatabase database=openHelper.getWritableDatabase();
            return  database.update("users",contentValues,s,strings);
        }else {
            return 0;
        }
    }
}
